#!/usr/bin/env python3
"""
异步功能演示启动脚本
启动MAESS系统并测试异步Agent调用功能
"""

import asyncio
import subprocess
import time
import requests
import json
from loguru import logger


def start_system():
    """启动MAESS系统"""
    logger.info("正在启动MAESS系统...")
    
    # 启动FastAPI应用
    process = subprocess.Popen([
        "python", "-m", "uvicorn",
        "main:app",
        "--host", "0.0.0.0",
        "--port", "8000",
        "--reload"
    ], cwd=r"c:\Users\Windows10\Desktop\MAESS\maess_-flow")
    
    logger.info("等待系统启动...")
    time.sleep(5)  # 等待系统启动
    
    return process


def test_async_endpoints():
    """测试异步端点"""
    base_url = "http://localhost:8000"
    
    logger.info("开始测试异步端点...")
    
    # 1. 测试健康检查
    try:
        response = requests.get(f"{base_url}/health", timeout=5)
        if response.status_code == 200:
            logger.success("✅ 系统健康检查通过")
        else:
            logger.error(f"❌ 健康检查失败: {response.status_code}")
            return False
    except Exception as e:
        logger.error(f"❌ 健康检查异常: {e}")
        return False
    
    # 2. 测试异步任务执行
    logger.info("测试异步任务执行...")
    
    async_task_payload = {
        "task_id": "demo_async_task_001",
        "task_type": "single",
        "agent_type": "text_qa",
        "input": "什么是异步编程？请用简单的语言解释",
        "priority": "normal",
        "timeout": 30
    }
    
    try:
        response = requests.post(f"{base_url}/api/async/task/execute", 
                               json=async_task_payload, timeout=35)
        
        if response.status_code == 200:
            result = response.json()
            logger.success(f"✅ 异步任务执行成功")
            logger.info(f"   任务ID: {result['task_id']}")
            logger.info(f"   执行时间: {result['execution_time']:.3f}s")
            logger.info(f"   状态: {result['status']}")
            
            if result.get('result', {}).get('answer'):
                answer = result['result']['answer'][:100] + "..." if len(result['result']['answer']) > 100 else result['result']['answer']
                logger.info(f"   回答预览: {answer}")
        else:
            logger.error(f"❌ 异步任务执行失败: {response.status_code} - {response.text}")
            return False
            
    except Exception as e:
        logger.error(f"❌ 异步任务执行异常: {e}")
        return False
    
    # 3. 测试批量异步任务
    logger.info("测试批量异步任务...")
    
    batch_tasks = []
    for i in range(5):
        batch_tasks.append({
            "task_id": f"demo_batch_task_{i+1}",
            "task_type": "single",
            "agent_type": "text_qa",
            "input": f"这是第{i+1}个批量任务问题",
            "priority": "normal",
            "timeout": 30
        })
    
    batch_payload = {
        "tasks": batch_tasks,
        "max_concurrent": 3
    }
    
    try:
        response = requests.post(f"{base_url}/api/async/task/batch", 
                               json=batch_payload, timeout=60)
        
        if response.status_code == 200:
            result = response.json()
            logger.success(f"✅ 批量任务执行成功")
            logger.info(f"   批次ID: {result['batch_id']}")
            logger.info(f"   总任务数: {result['total_tasks']}")
            logger.info(f"   成功任务: {result['completed_tasks']}")
            logger.info(f"   失败任务: {result['failed_tasks']}")
            logger.info(f"   总耗时: {result['total_time']:.3f}s")
        else:
            logger.error(f"❌ 批量任务执行失败: {response.status_code} - {response.text}")
            return False
            
    except Exception as e:
        logger.error(f"❌ 批量任务执行异常: {e}")
        return False
    
    # 4. 测试性能统计
    logger.info("测试性能统计接口...")
    
    try:
        response = requests.get(f"{base_url}/api/async/performance/stats", timeout=10)
        
        if response.status_code == 200:
            stats = response.json()
            logger.success("✅ 性能统计接口正常")
            
            perf = stats.get("async_performance", {})
            logger.info(f"   平均响应时间: {perf.get('average_response_time_ms', 0)}ms")
            logger.info(f"   并发处理能力: {perf.get('max_concurrent_tasks', 0)} tasks")
            logger.info(f"   当前活跃任务: {perf.get('current_active_tasks', 0)} tasks")
            logger.info(f"   成功率: {perf.get('success_rate', 0)*100:.1f}%")
        else:
            logger.error(f"❌ 性能统计接口异常: {response.status_code}")
            return False
            
    except Exception as e:
        logger.error(f"❌ 性能统计接口异常: {e}")
        return False
    
    return True


def main():
    """主函数"""
    logger.info("🚀 开始MAESS异步功能演示")
    
    # 启动系统
    process = start_system()
    
    try:
        # 等待系统完全启动
        time.sleep(3)
        
        # 测试异步功能
        success = test_async_endpoints()
        
        if success:
            logger.success("\n🎉 所有异步功能测试通过！")
            logger.info("\n📚 可用接口:")
            logger.info("   • 异步任务执行: POST /api/async/task/execute")
            logger.info("   • 批量异步任务: POST /api/async/task/batch")
            logger.info("   • 性能统计: GET /api/async/performance/stats")
            logger.info("   • 健康检查: GET /api/async/health")
            logger.info("\n🌐 访问 http://localhost:8000/api/docs 查看完整API文档")
            
            logger.info("\n⏰ 系统将继续运行，按 Ctrl+C 停止...")
            
            # 保持系统运行
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                logger.info("用户中断演示")
        else:
            logger.error("\n❌ 异步功能测试失败")
            
    except Exception as e:
        logger.error(f"演示过程异常: {e}")
        
    finally:
        # 停止系统
        logger.info("正在停止系统...")
        process.terminate()
        process.wait()
        logger.info("系统已停止")


if __name__ == "__main__":
    main()